package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import com.dropbox.chooser.android.DbxChooser;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class BrightnessActivity2 extends Activity {

	private static final int SELECT_PICTURE = 1;
	private static final int DBX_CHOOSER_REQUEST = 2;
	public static final int GALLERY_CHOOSER_INTENT = 3;
	

	private static Bitmap resizedbmp;
	private static String picturePath;
	public static Bitmap colorBmp;
	public Bitmap originalBmp; // original image
	public Bitmap activeBmp; // edited image
	Bitmap takenimg; // copy of edited image
	Bitmap brightbmp; // brightness changed image

	Button btImage, btRotate, btSave, btMirror;
	ImageView ivImage;
	SeekBar sbBrightness;
	TextView tvBrightness;
	float flip = 0;

	// seekbar values
	static int currentprogress;
	static int defaultprogress;
	static int posdifference;
	//dropbox
	private DbxChooser mChooser;
	//google drive
	

	public void setcolorBmp(Bitmap bmp) {
		this.colorBmp = bmp;
	}

	public void setPicturePath() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mChooser = new DbxChooser("nw23jo0zl97ioa8");
		//google
		/*mGoogleApiClient = new GoogleApiClient.Builder(this)
	    .addApi(Drive.API)
	    .addScope(Drive.SCOPE_FILE)
	    .addConnectionCallbacks((ConnectionCallbacks) BrightnessActivity2.this)
                .addOnConnectionFailedListener((OnConnectionFailedListener) BrightnessActivity2.this)
                .build();*/
		//
		Instantiate();

	}

	public void Instantiate() {

		setContentView(R.layout.brightnessactivity2);
		flip = 1.0f;
		// declare buttons, image views, seek bars
		tvBrightness = (TextView) findViewById(R.id.tvBrightness);
		ivImage = (ImageView) findViewById(R.id.ivImage);
		btImage = (Button) findViewById(R.id.btImage);
		btSave = (Button) findViewById(R.id.btSave);
		btRotate = (Button) findViewById(R.id.btRotate);
		sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);

		// don't allow user to click button when no pic is loaded
		btSave.setEnabled(false);
		btRotate.setEnabled(false);
		sbBrightness.setEnabled(false);
		

		// image selection
		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent();
				// intent.setType("image/*");
				// intent.setAction(Intent.ACTION_GET_CONTENT);

				// startActivityForResult(
				// Intent.createChooser(intent, "Select Picture"),
				// SELECT_PICTURE);
				
				//galleries only
				//Intent intent = new Intent(Intent.ACTION_PICK);
				//intent.setType("image/*");
				//startActivityForResult(intent, SELECT_PICTURE);
				
				//dropbox
				// mChooser.forResultType(DbxChooser.ResultType.FILE_CONTENT)
				// .launch(BrightnessActivity2.this, DBX_CHOOSER_REQUEST);
				Intent intent = new Intent();
	            intent.setType("image/*");
	            intent.setAction(Intent.ACTION_GET_CONTENT);
	            startActivityForResult(intent, GALLERY_CHOOSER_INTENT);
			}
		});
		// save button
		btSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});
		// rotation button
		btRotate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent goToNextActivity = new Intent(getApplicationContext(),
						RotationActivity.class);
				byte[] bytes = compressImage(activeBmp);
				goToNextActivity.putExtra("BMP", bytes);
				// coloured image passing
				// byte[] colorbytes = compressImage(colorBmp);
				// goToNextActivity.putExtra("colorBmp", colorbytes);
				startActivity(goToNextActivity);
			}
		});
		// mirror button
		btMirror = (Button) findViewById(R.id.btMirror);
		btMirror.setEnabled(false);
		btMirror.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// create new matrix for transformation
				if (originalBmp != null) {
					Matrix matrix = new Matrix();

					// matrix.preScale(-1.0f, 1.0f);
					/*
					 * if (flip == 1.0f) { flip = -1.0f; matrix.preScale(flip,
					 * 1.0f); } else { flip = 1.0f; matrix.preScale(flip, 1.0f);
					 * }
					 */

					matrix.setScale(-1.0f, 1.0f);

					if (activeBmp == null) {
						Bitmap resizedbmp1 = Bitmap.createBitmap(originalBmp,
								0, 0, originalBmp.getWidth(),
								originalBmp.getHeight(), matrix, true);
						Bitmap resizedbmp = Bitmap.createScaledBitmap(
								resizedbmp1, 300, 300, true);
						ivImage.setImageBitmap(resizedbmp);
						activeBmp = resizedbmp1;
						// flip the original image also
						Bitmap colorBmp1 = Bitmap.createBitmap(colorBmp, 0, 0,
								colorBmp.getWidth(), colorBmp.getHeight(),
								matrix, true);
						setcolorBmp(colorBmp1);
					} else {
						Bitmap resizedbmp1 = Bitmap.createBitmap(activeBmp, 0,
								0, activeBmp.getWidth(), activeBmp.getHeight(),
								matrix, true);
						Bitmap resizedbmp = Bitmap.createScaledBitmap(
								resizedbmp1, 300, 300, true);
						ivImage.setImageBitmap(resizedbmp);
						activeBmp = resizedbmp1;
						// flip the original image also
						Bitmap colorBmp1 = Bitmap.createBitmap(colorBmp, 0, 0,
								colorBmp.getWidth(), colorBmp.getHeight(),
								matrix, true);
						setcolorBmp(colorBmp1);
					}
				}

			}
		});

		sbBrightness.incrementProgressBy(1);
		sbBrightness.setProgress(50);
		sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (takenimg == null) {
					takenimg = originalBmp;
				}
				currentprogress = sbBrightness.getProgress();
				int alpha = 1;
				int progressvalue = currentprogress;
				int beta = progressvalue - 50;
				// int beta = 10;
				// int progressvalue = currentprogress - 50;
				// int alpha = progressvalue / 10;

				if (alpha != 0) {
					Mat srcImg = new Mat(takenimg.getHeight(), takenimg
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenimg.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);

					Mat destination = new Mat(srcImg.rows(), srcImg.cols(),
							srcImg.type());
					srcImg.convertTo(destination, -1, alpha, beta);
					// convert back to bitmap
					Utils.matToBitmap(destination, myBitmap32);
					activeBmp = myBitmap32;
					// set imageview and seekbar
					Bitmap resizedbmp = Bitmap.createScaledBitmap(myBitmap32,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);
					sbBrightness.setProgress(currentprogress);
					tvBrightness.setText("Brightness: " + beta);
				} else {
					Bitmap resizedbmp = Bitmap.createScaledBitmap(originalBmp,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);
					sbBrightness.setProgress(currentprogress);
					tvBrightness.setText("Brightness: " + alpha);
				}
				/*
				 * currentprogress = sbBrightness.getProgress(); defaultprogress
				 * = 50; int difference = currentprogress - defaultprogress; int
				 * brightness = difference;
				 * 
				 * int display = currentprogress - 50;
				 * 
				 * brightbmp = doBrightness(takenimg, difference); Bitmap
				 * resizedbmp = Bitmap.createScaledBitmap(brightbmp, 300, 300,
				 * true); ivImage.setImageBitmap(resizedbmp);
				 * sbBrightness.setProgress(currentprogress);
				 * tvBrightness.setText("Brightness: " + display);
				 * 
				 * activeBmp = brightbmp;
				 */

			}
		});

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK
				&& null != data) {

			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			picturePath = cursor.getString(columnIndex);
			cursor.close();
			takenimg = null;
			//originalBmp = null;
			//colorBmp = null;
			originalBmp = BitmapFactory.decodeFile(picturePath);
			colorBmp = BitmapFactory.decodeFile(picturePath);
			activeBmp = BitmapFactory.decodeFile(picturePath);
			/*
			 * originalBmp = Bitmap .createScaledBitmap(originalBmp, 1900,
			 * ((1900 * originalBmp .getHeight()) / originalBmp.getWidth()),
			 * true);
			 */
			if (originalBmp.getWidth() > originalBmp.getHeight()) {
				if (originalBmp.getWidth() > 800) {
					originalBmp = Bitmap.createScaledBitmap(originalBmp, 800,
							((800 * originalBmp.getHeight()) / originalBmp
									.getWidth()), true);
					colorBmp = Bitmap.createScaledBitmap(colorBmp, 800,
							((800 * colorBmp.getHeight()) / colorBmp
									.getWidth()), true);
				}
			} else {
				if (originalBmp.getHeight() > 800) {
					originalBmp = Bitmap.createScaledBitmap(originalBmp,
							((800 * originalBmp.getWidth()) / originalBmp
									.getHeight()), 800, true);
					colorBmp = Bitmap.createScaledBitmap(colorBmp,
							((800 * colorBmp.getWidth()) / colorBmp
									.getHeight()), 800, true);

				}
			}
			Log.d("tag1", "original bmp height: " + originalBmp.getHeight());
			Log.d("tag1", "original bmp width: " + originalBmp.getWidth());
			Log.d("tag1", "color bmp height: " + colorBmp.getHeight());
			Log.d("tag1", "color bmp width: " + colorBmp.getWidth());

			// convert bitmap to matrix
			Mat srcImg = new Mat(originalBmp.getHeight(),
					originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
			Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888, true);
			Utils.bitmapToMat(myBitmap32, srcImg);

			// convert to grayscale
			Mat grayImg = new Mat();
			Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
			originalBmp = Bitmap.createBitmap(grayImg.cols(), grayImg.rows(),
					Bitmap.Config.RGB_565);

			// convert mat back to bitmap set originalBmp
			Utils.matToBitmap(grayImg, originalBmp);
			// set activeBmp
			activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);
			// activeBmp = originalBmp;
			// resized bitmap to fit image view
			resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, 300, true);
			ivImage.setImageBitmap(resizedbmp);
			sbBrightness.setProgress(50);
			// allow users to click buttons
			btSave.setEnabled(true);
			btRotate.setEnabled(true);
			sbBrightness.setEnabled(true);
			btMirror.setEnabled(true);
		} else if (requestCode == DBX_CHOOSER_REQUEST) {
			if (resultCode == Activity.RESULT_OK) {
				DbxChooser.Result result = new DbxChooser.Result(data);
				// Log.d("tag1", "Link to selected file: " + result.getLink());
				Uri selectedImage = result.getLink();
				InputStream imageStream = null;
				try {
					imageStream = getContentResolver().openInputStream(
							selectedImage);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

				Bitmap bmp = BitmapFactory.decodeStream(imageStream);

				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
				byte[] byteArray = stream.toByteArray();
				try {
					stream.close();
					stream = null;
				} catch (IOException e) {

					e.printStackTrace();
				}

				Bitmap dbbitmap = BitmapFactory.decodeByteArray(byteArray, 0,
						byteArray.length);

				takenimg = null;
				originalBmp = dbbitmap;
				colorBmp = dbbitmap;

				if (originalBmp.getWidth() > originalBmp.getHeight()) {
					if (originalBmp.getWidth() > 1000) {
						originalBmp = Bitmap.createScaledBitmap(originalBmp,
								1000,
								((1000 * originalBmp.getHeight()) / originalBmp
										.getWidth()), true);
						colorBmp = Bitmap.createScaledBitmap(colorBmp, 1000,
								((1000 * colorBmp.getHeight()) / colorBmp
										.getWidth()), true);
					}
				} else {
					/*
					 * if (originalBmp.getHeight() > 1000) { originalBmp =
					 * Bitmap.createScaledBitmap(originalBmp, 1000, ((1000 *
					 * originalBmp.getHeight()) / originalBmp .getWidth()),
					 * true); }
					 */
					if (originalBmp.getHeight() > 1000) {
						originalBmp = Bitmap.createScaledBitmap(originalBmp,
								((1000 * originalBmp.getWidth()) / originalBmp
										.getHeight()), 1000, true);
						colorBmp = Bitmap.createScaledBitmap(colorBmp,
								((1000 * colorBmp.getWidth()) / colorBmp
										.getHeight()), 1000, true);

					}
				}
				Log.d("tag1", "original bmp height: " + originalBmp.getHeight());
				Log.d("tag1", "original bmp width: " + originalBmp.getWidth());
				Log.d("tag1", "color bmp height: " + colorBmp.getHeight());
				Log.d("tag1", "color bmp width: " + colorBmp.getWidth());

				// convert bitmap to matrix
				Mat srcImg = new Mat(originalBmp.getHeight(),
						originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
				Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888,
						true);
				Utils.bitmapToMat(myBitmap32, srcImg);

				// convert to grayscale
				Mat grayImg = new Mat();
				Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
				originalBmp = Bitmap.createBitmap(grayImg.cols(),
						grayImg.rows(), Bitmap.Config.RGB_565);

				// convert mat back to bitmap set originalBmp
				Utils.matToBitmap(grayImg, originalBmp);
				// set activeBmp
				activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);
				// activeBmp = originalBmp;
				// resized bitmap to fit image view
				resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, 300,
						true);
				ivImage.setImageBitmap(resizedbmp);
				sbBrightness.setProgress(50);
				// allow users to click buttons
				btSave.setEnabled(true);
				btRotate.setEnabled(true);
				sbBrightness.setEnabled(true);
				btMirror.setEnabled(true);

				// Handle the result
			} else {
				// Failed or was cancelled by the user.
			}
		} 
		else if (requestCode == GALLERY_CHOOSER_INTENT) {
            // Get the filepath and display on imageview.
            String filepath = getGalleryImagePath(data);
            // Check if the specified image exists.
            if (!new File(filepath).exists()) {
                Toast.makeText(this, "Image does not exist.", Toast.LENGTH_SHORT).show();
            } else {
                // Display image in ImageView.
                Bitmap img = BitmapFactory.decodeFile(filepath);
                //ivImage.setImageBitmap(img);
                
                originalBmp = img;
    			colorBmp = img;
    			activeBmp = img;
    			/*
    			 * originalBmp = Bitmap .createScaledBitmap(originalBmp, 1900,
    			 * ((1900 * originalBmp .getHeight()) / originalBmp.getWidth()),
    			 * true);
    			 */
    			if (originalBmp.getWidth() > originalBmp.getHeight()) {
    				if (originalBmp.getWidth() > 800) {
    					originalBmp = Bitmap.createScaledBitmap(originalBmp, 800,
    							((800 * originalBmp.getHeight()) / originalBmp
    									.getWidth()), true);
    					colorBmp = Bitmap.createScaledBitmap(colorBmp, 800,
    							((800 * colorBmp.getHeight()) / colorBmp
    									.getWidth()), true);
    				}
    			} else {
    				if (originalBmp.getHeight() > 1000) {
    					originalBmp = Bitmap.createScaledBitmap(originalBmp,
    							((800 * originalBmp.getWidth()) / originalBmp
    									.getHeight()), 800, true);
    					colorBmp = Bitmap.createScaledBitmap(colorBmp,
    							((800 * colorBmp.getWidth()) / colorBmp
    									.getHeight()), 800, true);

    				}
    			}
    			Log.d("tag1", "original bmp height: " + originalBmp.getHeight());
    			Log.d("tag1", "original bmp width: " + originalBmp.getWidth());
    			Log.d("tag1", "color bmp height: " + colorBmp.getHeight());
    			Log.d("tag1", "color bmp width: " + colorBmp.getWidth());

    			// convert bitmap to matrix
    			Mat srcImg = new Mat(originalBmp.getHeight(),
    					originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
    			Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888, true);
    			Utils.bitmapToMat(myBitmap32, srcImg);

    			// convert to grayscale
    			Mat grayImg = new Mat();
    			Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
    			originalBmp = Bitmap.createBitmap(grayImg.cols(), grayImg.rows(),
    					Bitmap.Config.RGB_565);

    			// convert mat back to bitmap set originalBmp
    			Utils.matToBitmap(grayImg, originalBmp);
    			// set activeBmp
    			activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);
    			// activeBmp = originalBmp;
    			// resized bitmap to fit image view
    			resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, 300, true);
    			ivImage.setImageBitmap(resizedbmp);
    			sbBrightness.setProgress(50);
    			// allow users to click buttons
    			btSave.setEnabled(true);
    			btRotate.setEnabled(true);
    			sbBrightness.setEnabled(true);
    			btMirror.setEnabled(true);
            }
        } 
		
		else {
			super.onActivityResult(requestCode, resultCode, data);
		}

	}
	
	
	public String getGalleryImagePath(Intent data) {
        Uri imgUri = data.getData();
        String filePath = "";
        if (data.getType() == null) {
            // For getting images from default gallery app.
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(imgUri, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        } else if (data.getType().equals("image/jpeg") || data.getType().equals("image/png")) {
            // For getting images from dropbox or any other gallery apps.
            filePath = imgUri.getPath();
        }
        return filePath;
    }
	

	// this is for opencv
	public BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS:
				// DO YOUR WORK/STUFF HERE
				break;
			default:
				super.onManagerConnected(status);
				break;
			}
		}
	};

	// onresume is for the opencv
	@Override
	protected void onResume() {
		super.onResume();
		OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this,
				mOpenCVCallBack);
	}
}
